/**
 * Created by lihao on 2017/3/7.
 */
//接口服务
"use strict";
var Promise = require('bluebird');
var ApiService = require('./ApiService');

module.exports = function () {
    var userData = {};
    return {
        getUser: function () {
            var _this = this;
            if (_.isEmpty(userData)) {
                return ApiService.postApi('userInfo')
                    .then(ApiService.error)
                    .then(function (data) {
                        userData = data.data;
                        ApiService.setCookie('userId', data.data.userId);
                        $('body').trigger('userIsLoad');
                        return Promise.resolve(userData);
                    })
                    .catch(function (err) {
						window.location.href = '/login/login.html?returnUrl=' + encodeURIComponent(window.location.href);
                        return Promise.reject(err);
                    });
            } else {
                return Promise.resolve(userData);
            }

        },
        getUserData: function () {
            return userData;
        },
        login: function (params) {
            return ApiService.postApi('login', params)
                .then(ApiService.error)
                .then(function (data) {
                    var localUserId = ApiService.getCookie('userId');
                    var returnUrl = ApiService.getUrlParams('returnUrl');
                    if(!(localUserId == data.data.userId)){
                        returnUrl = '';
                    }
                    layer.msg(data.message);
                    if (_.isEmpty(returnUrl)) {
                        setTimeout(function () {
                            window.location.href = '/userCenter/workBench.html';
                        }, 1000)

                    } else {
                        setTimeout(function () {
                            window.location.href = decodeURIComponent(returnUrl);
                        }, 1000)
                    }
                })
        },
        logout: function () {
            var _this = this;
            return ApiService.postApi('logout', {})
                .then(ApiService.error)
                .then(function () {
                    layer.msg('注销成功！');
                    _this.status = false;
                    setTimeout(function () {
                        window.location.href = '/login/login.html?returnUrl=' + encodeURIComponent(window.location.href);
                    }, 1000);
                    return null;
                })
                .catch(function (err) {
                    setTimeout(function () {
                        window.location.href = '/login/login.html?returnUrl=' + encodeURIComponent(window.location.href);
                    }, 1000);
                });
        },
    }
}();
